import { Component, OnInit, Inject, ViewChild, ElementRef } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router'; 
import { AgreementService } from "./time-deposit.service";
import { AppPaginationComponent, PaginationModel } from '../../../widgets/pagination/pagination.component';
import { environment } from '../../../../environments/environment';
import { Util } from "../../../common/util";
import * as moment from 'moment';
import * as _ from 'lodash';
import { FileUploader } from "ng2-file-upload";

@Component({
	selector: 'deposit-time-deposit',
	templateUrl: './time-deposit.component.html',
	styleUrls: ['./time-deposit.component.scss'],
	providers:[AgreementService]
})
export class TimeDepositComponent implements OnInit {
	public $ = window['$'];
	// 全选按钮
	public isCheckedAll= false;
	// 是否为指定ID查询
	public displayModel = 'agreeList';
	// 提前支取实例
	public advenceOne: any= {};
	// 提前支取列表
	public AdvenceList: Array<any>;
	// 查询条件
	public searchBody: any= {
		advenceId: "",
		page:1,
		pageSize: environment.pageSize
	}
	// 定存协议查询ID
	public lAgreeNo= "";
	// 定存协议列表
	public AgreeList: Array<any>;
	// 定存协议信息
	public AgreeOne:any;
	// 新增定存协议模版
	public addAgreeInfoModel: any= {
		vcAgreesim: "",                        // 银行简称
		vcAgreeName: "",                       // 银行全称
		vcZbankNo: "",                         // 总行代码
		vcZbankName: "",                       // 总行名称
		vcFzname: "",                          // 负责人名称
		vcFzaddr: "",                          // 负责人地址
		vcZdname: "",                          // 指定人名称
		vcZdidno: "",                          // 指定人身份证号
		vcZdtel: "",                           // 指定人电话
		vcZdmob: "",                           // 指定人手机
		vcZdfax: "",                           // 指定人传真
		vcZdzip: "",                           // 指定人邮编
		vcZdaddr: "",                          // 指定人地址
		vcCreator: "",                         // 创建者
		vcState: "",                           // 1，待审核(新建必填1)
	}
	// 定存协议复核模版
	public fhAgreeInfoModel: any= {
		lAgreeNo: "",                          // 定存协议ID
		vcState: ""                            // 模板状态：0，审核通过；1，待审核；2，被打回
	}
	// 新增定存银行账户配置模版
	public addDepositBankModel: any= {
		vcBankName: "",                        // 开户行名称
		vcFullbankName: "",                    // 开户行全称
		vcZbankNo: "",                         // 总行代码
		vcZbankName: "",                       // 总行名称
		vcAgreeNo: "",                         // 分行代码
		vcAgreeName: "",                       // 分行名称
		vcZhname: "",                          // 开户名称
		vcZhcode: "",                          // 开户帐号
		vcProvinceId: "",                      // 省份ID
		vcProvinceName: "",                    // 省份
		vcCityId: "",                          // 城市ID
		vcCityName: "",                        // 城市
		vcFundCode: "",                        // 基金代码
		vcCreator: "",                         // 创建者
		vcPayno: "",                           // 支付编号
		vcZhmaxpay: "",                        // 大额支付号
		vcTgzg: ""                             // 过滤条件
	} 
	// 定存账户配置查询银行ID
	public lBankNo;
	// 定存账户配置查询基金代码
	public FundCode;
	// 定存银行账户列表
	public DepositBankList: Array<any>;
	// 新增提前支取
	public advence: any= {
		vcFundNo: "",                          // 基金内码
		vcFundName: "",                        // 基金名称
		vcFundCode: "",                        // 基金代码
		vcBankname: "",                        // 存款行
		vcCapital: "",                         // 定存金额
		vcAdvenceCapital: "",                  // 提前支取金额
		vcAdvenceDay: "",                      // 提前支取日期
		vcAdvenceInterest: "",                 // 提前支取利息
		vcAdvenceRate: "",                     // 提前支取利率
		vcAccountantNo: ""                     // 主办会计
	} 
	// 新增-定存信息列表
	public DepositList: Array<any>;
	// 新增-定存信息查询模版
	public depositInfoBody: any= {
		vcFundCode: "",
		page:1,
		pageSize: environment.pageSize
	}
	// 剩余金额
	public leftMoneyModel: any={
		vcFundCode: "",
		leftMoney: ""
	}
	// 提前支取存单信息查询ID
	public lDepositNo;
	// 提前支取存单信息列表
	public DepositAdvenceList: Array<any>;
	// 提前支取分页配置
	public pageInfo: PaginationModel = {
		currentPageNum: 1,
		totalPages: 1,
        pageSize: 10,
        total: 0,
        pagesShow: 5,
        startRow: 0,
        endRow: 0,
		pageList: [5, 10, 25, 50, 100]
	}
	// 定存信息分页配置
	public depositInfoPage: PaginationModel = {
		currentPageNum: 1,
		totalPages: 1,
        pageSize: 5,
        total: 0,
        pagesShow: 5,
        startRow: 0,
        endRow: 0,
		pageList: [5, 10, 25, 50, 100]
	}
	// 分页组件
	@ViewChild(AppPaginationComponent)
	public paginationComponent: AppPaginationComponent;
	constructor(public agreementService: AgreementService,public router: Router) {
	}
	 // 初始化定义uploader变量,用来配置input中的uploader属性
	 public uploader: FileUploader = new FileUploader({});
	 // 上传文件的名称
	 public uploadFileName: any= "";
	 // 选择文件状态
	 public fileStatus= false;
	// 列表数据初始化
	ngOnInit() {
		this.getAgreeList();
	}
	// 日期插件初始化
	ngAfterViewInit(): void {
		Util.datepickerPluginInit(".datepicker-plugin");
	}
////////////////////////////////////////////////////////////////////////////////////////////
	// 提前支取列表
	gotoAdvenceList(){
		this.getAdvenceList();
		this.displayModel= 'advenceList';
	}
	// 获取提前支取列表
	getAdvenceList(){
		var that = this;
		this.searchBody.page= this.pageInfo.currentPageNum;
		this.searchBody.pageSize= this.pageInfo.pageSize;
		if (this.searchBody.advenceId == "") {
			this.agreementService.getAdvenceList(this.searchBody).subscribe(data=> {
				if (data) {
					that.AdvenceList= _.pull(data.list,null);
					that.pageInfo.totalPages = data.pages;          // 总页数
					that.pageInfo.total= data.total;                // 数据总个数
					that.displayModel= 'advenceList';
				}else{
					window['swal']("失败","获取数据失败!","error");
				}
				console.log("总记录数："+that.pageInfo.total);
			})
		}else{
			this.agreementService.getAdvence(this.searchBody.advenceId).subscribe(data=> {
				if (data){
					that.advenceOne = _.pull(data,null);
					//that.editAdvence= _.clone(that.advenceOne);
					that.displayModel= 'advenceOne';
				}else{
					window['swal']("失败","查询失败！","error");
					that.resetSearch();
				}
			})
		}
	}
	// 重置查询 
	resetSearch(){
		this.searchBody.advenceId= "";
		this.pageInfo.currentPageNum= 1;
	}
	// 根据页码显示数据
	getCurrentPageNum(currentNum){
		this.pageInfo.currentPageNum = currentNum;
		this.getAdvenceList();
	}
	// 新增提前支取 
	addAdvence(){
		let that = this;
		window["swal"](
			{
				title: "提示！",
				text: "是否确定新增 "+this.advence.vcFundName+" 提前支取?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			    function(isConfirm) {
					if (isConfirm) { // 确认
						that.advence.vcAdvenceDay = that.$(".datepicker-plugin").val();
						that.agreementService.addAdvence(that.advence).subscribe(data => {
							if(data) {
								console.log(JSON.stringify(that.advence));
								window["swal"]("成功", "新增成功", "success");
								that.toggleModal('addModal');
								that.resetAddAdvence();
								that.getAdvenceList();                          // 重新加载列表数据
							}
						});
					} else { 
					// 取消
				}
			}
		);
	}
	// 重置新增
	resetAddAdvence(){
		this.depositInfoBody.vcFundCode= "";
		this.advence.vcFundNo= "";
		this.advence.vcFundName= "";
		this.advence.vcBankname= "";
		this.advence.vcCapital= "";
		this.advence.vcAdvenceCapital= "";
		this.advence.vcAdvenceInterest= "";
		this.advence.vcAdvenceDay= "";
		this.advence.vcAdvenceRate= "",
		this.advence.vcAccountantNo= "",
		this.$('.datepicker-plugin').val("");
	}
	// 新增-获取定存信息
	getDepositList(){
		let that = this;
		this.depositInfoBody.page= this.depositInfoPage.currentPageNum;
		this.depositInfoBody.pageSize= this.depositInfoPage.pageSize;
		this.agreementService.getDepositList(this.depositInfoBody).subscribe(data=> {
			if(data){
				that.DepositList= _.pull(data.list,null);
				that.depositInfoPage.totalPages = data.pages;          // 总页数
				that.depositInfoPage.total= data.total;                // 总个数
				that.$('#depositListModal').modal('show');
			}else{
				window['swal']("提取失败","请检查是否输入有误","error");
			}
		})
	}
	// 根据页码获取定存信息列表
	getDepositInfoPageNum(currentPageNum: number) {
		this.depositInfoPage.currentPageNum = currentPageNum;
		this.getDepositList();
	}
	// 获取新增存单信息
	getDepositInfo(depositInfo){
		this.advence.vcFundCode= depositInfo.vcFundCode;
		this.advence.vcFundNo= depositInfo.vcFundNo;
		this.advence.vcFundName= depositInfo.vcFundName;
		this.advence.vcBankname= depositInfo.vcFullbankkname;
		this.advence.vcCapital= depositInfo.vcAmount;
		this.toggleModal('depositListModal');
	}
	// 基金经理确认
	managerConfirm(advenceInfo){
		let that = this;
		window["swal"](
			{
				title: "提示！",
				text: "是否确认 "+advenceInfo.vcFundName+" 提前支取?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			    function(isConfirm) {
					if (isConfirm) {
						that.agreementService.managerConfirm(advenceInfo.lAdvenceNo).subscribe(data => {
							if(data == true) {
								window["swal"]("成功", "已确认", "success");
								that.getAdvenceList();                          
							}
						})
					}
				} 
		)
	}
	// 会计核对
	accountingCheck(advenceInfo){
		let that = this;
		window["swal"](
			{
				title: "提示！",
				text: "是否核对 "+advenceInfo.vcFundName+" 提前支取?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			    function(isConfirm) {
					if (isConfirm) {
						that.agreementService.accountingCheck(advenceInfo.lAdvenceNo).subscribe(data => {
							if(data == true) {
								window["swal"]("成功", "已核对", "success");
								that.getAdvenceList();                          
							}
						})
					}
				}
		)
	}
	// 定存协议列表
	gotoAgreeList(){
		this.getAgreeList();
		this.displayModel= 'agreeList';
	}
	// 重置查询
	resetlAgreeNo(){
		this.lAgreeNo= "";
	}
	// 获取定存协议列表
	getAgreeList(){
		let that = this;
		if(this.lAgreeNo == ""){
			this.agreementService.getAgreeList().subscribe(data=> {
				if(data){
					that.AgreeList= _.pull(data,null);
					that.displayModel= 'agreeList';
				}else{
					window["swal"]("失败", "获取协议列表失败!", "error");
				}
			})
		}else{
			this.agreementService.getAgreeInfo(this.lAgreeNo).subscribe(data=> {
				if(data){
					that.AgreeOne= _.pull(data,null);
					that.displayModel= 'agreeOne';
				}else{
					window["swal"]("失败", "查询失败!", "error");
				}
				
			})
		}
	}
	// 新增定存协议
	addAgreeInfo(){
		let that= this;
		window["swal"](
			{
				title: "提示！",
				text: "是否新增 "+this.addAgreeInfoModel.vcAgreeName+" 协议配置?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			function(isConfirm) {
				if (isConfirm) {
					that.agreementService.addAgreeInfo(that.addAgreeInfoModel).subscribe(data=> {
						if(data == true) {
							window["swal"]("成功", "新增完成", "success");
							that.resetaddAgreeModel()
							that.getAgreeList();                     
						}else{
							that.resetaddAgreeModel()
							window["swal"]("失败", "新增失败", "error");
						}
					})
				}
			}
		)
	}
	// 重置定存协议新增模版
	resetaddAgreeModel(){
		this.addAgreeInfoModel.vcAgreesim= "";                  
		this.addAgreeInfoModel.vcAgreeName= "";
		this.addAgreeInfoModel.vcZbankNo= "";                 
		this.addAgreeInfoModel.vcZbankName= "";                    
		this.addAgreeInfoModel.vcFzname= "";                       
		this.addAgreeInfoModel.vcFzaddr= "";                       
		this.addAgreeInfoModel.vcZdname= "";                       
		this.addAgreeInfoModel.vcZdidno= "";                       
		this.addAgreeInfoModel.vcZdtel= "";                      
		this.addAgreeInfoModel.vcZdmob= "";                           
		this.addAgreeInfoModel.vcZdfax= "";                           
		this.addAgreeInfoModel.vcZdzip= "";                         
		this.addAgreeInfoModel.vcZdaddr= "";                          
		this.addAgreeInfoModel.vcDqattach= "";                      
		this.addAgreeInfoModel.vcJdattach= "";                       
		this.addAgreeInfoModel.vcCreator= "";                                           
		this.addAgreeInfoModel.vcState= "";                          
	}
	// 复核定存协议配置
	fhAgreeInfo(){
		let that= this;
		window["swal"](
			{
				title: "提示！",
				text: "是否确认复核协议?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			function(isConfirm) {
				if (isConfirm) {
					that.agreementService.fhAgreeInfo(that.fhAgreeInfoModel).subscribe(data=> {
						if(data) {
							window["swal"]("成功", "完成复核", "success");
							that.resetfhAgreeInfo();
							that.toggleModal('fhAgreeModel');
							that.getAgreeList();
						}
					})
				}
			}
		)
	}
	// 重置复核信息模版
	resetfhAgreeInfo(){
		this.fhAgreeInfoModel.lAgreeNo= "";
		this.fhAgreeInfoModel.vcState= "";
	}
	// 定存银行账户管理
	gotoDepositBank(){
		this.displayModel= 'DepositBank';
	}
	// 新增定存银行账户配置
	addDepositBankInfo(){
		let that= this;
		window["swal"](
			{
				title: "提示！",
				text: "是否确认新增 "+this.addDepositBankModel.vcZhname+"银行账户?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			function(isConfirm) {
				if (isConfirm) {
					that.agreementService.addDepositBankInfo(that.addDepositBankModel).subscribe(data=> {
						if(data) {
							window["swal"]("成功", "新增成功", "success");
							that.toggleModal('addDepositBankModel');
						}
					})
				}
			}
		)	
	}
	// 重置新增定存银行账户模版
	resetAddDepositBankInfo(){
		this.addDepositBankModel.vcBankName= "";                        // 开户行名称
		this.addDepositBankModel.vcFullbankName= "";                    // 开户行全称
		this.addDepositBankModel.vcZbankNo= "";                         // 总行代码
		this.addDepositBankModel.vcZbankName= "";                       // 总行名称
		this.addDepositBankModel.vcAgreeNo= "";                         // 分行代码
		this.addDepositBankModel.vcAgreeName= "";                       // 分行名称
		this.addDepositBankModel.vcZhname= "";                          // 开户名称
		this.addDepositBankModel.vcZhcode= "";                          // 开户帐号
		this.addDepositBankModel.vcProvinceId= "";                      // 省份ID
		this.addDepositBankModel.vcProvinceName= "";                    // 省份
		this.addDepositBankModel.vcCityId= "";                          // 城市ID
		this.addDepositBankModel.vcCityName= "";                        // 城市
		this.addDepositBankModel.vcFundCode= "";                        // 基金代码
		this.addDepositBankModel.vcCreator= "";                         // 创建者
		this.addDepositBankModel.vcPayno= "";                           // 支付编号
		this.addDepositBankModel.vcZhmaxpay= "";                        // 大额支付号
		this.addDepositBankModel.vcTgzg= "";                            // 过滤条件
	}
	// 根据银行ID查询定存银行账户信息
	getBankInfoByBankId(){
		let that= this;
		this.agreementService.getBankInfoByBankId(this.lBankNo).subscribe(data=> {
			if(data){
				that.DepositBankList= _.pull(data,null);
				that.displayModel= 'DepositBank';
			}else{
				window["swal"]("失败", "请输入银行ID", "error");
			}
		})
	}
	// 根据基金代码查询定存银行账户信息
	getBankInfoByFundCode(){
		let that= this;
		this.agreementService.getBankInfoByFundCode(this.FundCode).subscribe(data=> {
			if(data){
				that.DepositBankList= _.pull(data,null);
				that.displayModel= 'DepositBank';
			}else{
				window["swal"]("失败", "请输入基金代码", "error");
			}
		})
	}
	// 重置定存银行账户信息查询银行ID
	resetlBankNo(){
		this.lBankNo= "";
	}
	// 重置定存银行账户信息查询基金代码
	resetFundCode(){
		this.FundCode= "";
	}
	// 剩余金额
	getLeftMoney(){
		let that = this;
		this.agreementService.getLeftMoney(this.leftMoneyModel.vcFundCode).subscribe(data=> {
			if(data){
				that.leftMoneyModel.leftMoney= _.pull(data,null);
			}else{
				window['swal']("失败","查询失败!","error");
			}
		})
	}
	resetLeftMoney(){
		this.leftMoneyModel.vcFundCode= "";
		this.leftMoneyModel.leftMoney= ""
	}
	// 提前支取存单信息列表
	gotoDepositAdvenceList(){
		this.displayModel= 'depositAdvenceList';
	}
	// 提前支取存单信息列表查询
	getDepositAdvenceList(){
		let that= this;
		this.agreementService.getDepositAdvenceList(this.lDepositNo).subscribe(data=> {
			if(data){
				that.DepositAdvenceList= _.pull(data,null);
			}else{
				window['swal']("失败","请输入定存编号!","error");
			}
		})
	}
	// 重置提前支取存单信息列表查询ID
	resetlDepositNo(){
		this.lDepositNo= "";
	}
	// 获取上传文件的名称
	selectedFileOnChanged(event: any){
		this.uploadFileName= event.target.value;
		this.fileStatus= true;
	}
	// 上传文件
	uploadFile(){
		let that = this;
		let fileItem = _.last(this.uploader.queue);
		fileItem.url = 'http://legiontest.zhuwenda.com:12042/otc/v1/TimeDepost/DepositAgree/InputAgree/'+this.fhAgreeInfoModel.lAgreeNo+'?token=2';
		fileItem.method = "POST";
		fileItem.alias = this.uploadFileName;
		// fileItem.headers = [{name: 'token', value: sessionStorage.getItem('username')}];

		// 开始上传
		fileItem.upload(); 

		// 上传一个文件成功的回调
		fileItem.onSuccess = function (response, status, headers) {
			let resVal = JSON.parse(response);
			// 上传文件成功,返回的code,一般0代表成功
			if (resVal.code + "" === "0") {
				// 上传文件后获取服务器返回的数据
				window["swal"]("成功", "导入成功", "success");
				// 上传成功后清空文件上传队列
				that.clearFileQueue();
			}else{
				window["swal"]("失败", "导入失败", "error");
				that.clearFileQueue();
			}
		};

		// 接口暂时不能用
		window["swal"]("sorry", "接口暂时不能用", "success");
	}
	// 清除FileUploader上传队列中的所有文件
	clearFileQueue() {
		this.uploader.clearQueue();
		this.fileStatus= false;
		this.$('#XCFile').val("");
	}

	// 弹出框
	toggleModal(id,agreeList?) {
		var formatedId = "#" + id;
		this.$(formatedId).modal('toggle');
		if (agreeList) {
			this.fhAgreeInfoModel.lAgreeNo= _.clone(agreeList.lAgreeNo);
		}
	}
	// 删除
	look(){
		window['swal']("sorry","接口暂时无法使用!","success");
	}
	// 全选或全不选
	// selectAll(){
	// 	if(this.isCheckedAll){
	// 		_.forEach(this.AdvenceList, item=> {
	// 			item.isChecked = true;
	// 		})
	// 	}else{
	// 		_.forEach(this.AdvenceList, item=> {
	// 			item.isChecked = false;
	// 		})
	// 	}
	// }
	// 存款账户管理
	// gotoAccountManage(){
	// 	this.router.navigateByUrl("pages/deposit/accountManage");
	// }
}
